package cron

import (
	"awesomeTask/application/client"
	"awesomeTask/application/models/programe"
	"awesomeTask/application/models/schdule"
	"awesomeTask/application/variable"
	"awesomeTask/commom/StringHelper"
	parseHelper "awesomeTask/commom/parse"
	"awesomeTask/system/crontab"
	"awesomeTask/system/log"
	"awesomeTask/system/rpc"
	"net"
	"strconv"
)

func LoadCronFromDataBase() {
	RemoveAllTask()
	schedule := schdule.LoadTaskFromDataBase()
	count := 0
	for _, i := range schedule {
		count++
		scheduleId := parseHelper.Int64ParseToString(i["id"].(int64))
		taskId := parseHelper.Int64ParseToString(i["task_id"].(int64))
		crontab.GetCronManager().AddTask(scheduleId, func() {
			if variable.IsMaster {
				RunTaskByTaskId(taskId, client.GetBestNode().Connetion)
			}
		}, i["cron_regx"].(string), i["name"].(string))
	}
	log.GetLogger().Warn("已经从数据库重载定时任务:" + strconv.Itoa(count) + "条")
}
func RemoveAllTask() {
	cronManager := crontab.GetCronManager()
	schdules := crontab.GetCronManager().GetTasks()
	for taskId, _ := range schdules {
		cronManager.RemoveTask(taskId)
	}
}
func RunTaskByTaskId(taskId string, clientCon net.Conn) (interface{}, error) {
	taskInfo := programe.GetTaskBaseInfo(taskId)
	taskInfo["uniqueTaskId"] = StringHelper.UniqueId(10)
	return rpc.RpcCall(variable.ON_RUN_TASK, taskInfo, clientCon, 5000)
}
